package com.yq.woshouCode;

import java.util.Arrays;

/**
 * @ClassName HeapSort
 * @Description 大顶堆
 * @Author yaoqiang
 * @Date 2021/2/7 9:11
 * @Version 1.0
 * <p>
 * [4, 6, 8, 5, 9]
 * [4, 9, 8, 5, 6]
 * [9, 4, 8, 5, 6]
 * [8, 4, 6, 5, 9]
 * [6, 4, 5, 8, 9]
 * [5, 4, 6, 8, 9]
 * [4, 5, 6, 8, 9]
 */
public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {4, 6, 8, 5, 9};
        System.out.println(Arrays.toString(arr));
        HeapSort(arr, 5);
    }

    /**
     * @param arr
     * @param length
     */
    public static void HeapSort(int[] arr, int length) {
       //第一个根节点 arr.length / 2
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            adjustHeap(arr, i, arr.length);
        }
        int temp = 0;
        for (int k = arr.length - 1; k > 0; k--) {
            temp = arr[k];
            arr[k] = arr[0];
            arr[0] = temp;
            adjustHeap(arr, 0, k);
        }
    }

    /**
     * 将arr数据的的第i个非叶子节点开始，将树调整成大顶堆
     * eg:传入i=1时 arr={4,6,8,5,9}-》arr={4,9,8,5,6}
     * 传入i=0 arr={4,9,8,5,6}->arr={9,4,8,5,6}
     *
     * @param arr
     * @param i
     * @param length
     */
    public static void adjustHeap(int[] arr, int i, int length) {
        int temp = arr[i];
        for (int k = 2 * i + 1; k < length; k = k * 2 + 1) {
            if (k + 1 < length && arr[k] < arr[k + 1]) {
                k++;
            }
            if (arr[i] < arr[k]) {
                arr[i] = arr[k];
                i = k;
            } else {
                break;
            }

        }
        arr[i] = temp;
        System.out.println(Arrays.toString(arr));
    }
}
